import {defineComponent, ref} from 'vue';
import {Button, Modal} from 'ant-design-vue';
import AddDynamicForm, {FieldConfig} from "../../form/AddDynamicForm.tsx";

export default defineComponent({
    name: 'AddFormModal',
    props: {
        fields: {
            type: Array as () => Array<FieldConfig>,
            required: true,
        },
        modelValue: {
            type: Object as () => Record<string, any>,
            required: true,
        },
        onSubmit: {
            type: Function as () => (values: Record<string, any>) => void,
            required: true,  // 提交动作通过props提供
        },
    },
    setup(props) {

        const isModalVisible = ref(false);
        const localModelValue = ref({...props.modelValue});  // 创建本地副本

        const showModal = () => {
            isModalVisible.value = true;
        };

        // 关闭表单模态框
        const handleCancel = () => {
            isModalVisible.value = false;
            localModelValue.value = {};  // 清空本地副本
            cleanData();  // 清空表单数据
        };

        // 假设模态框有一个 onClose 事件处理函数
        const cleanData = () => {
            Object.keys(localModelValue.value).forEach(key => {
                localModelValue.value[key] = '';  // 清空本地副本中的每个字段的值
            });
        };

        return () => (
            <div>
                <Button type="primary" onClick={showModal}>
                    添加
                </Button>
                <Modal
                    title="添加信息"
                    visible={isModalVisible.value}
                    onCancel={handleCancel}
                    footer={null}
                    width={600}
                >
                    <AddDynamicForm v-model={localModelValue.value} fields={props.fields} onSubmit={props.onSubmit}/>
                </Modal>
            </div>
        );
    }
});